package com.demo.security.ssl;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.TrustManagerFactory;

/**
 * SSL通信服务端
 *
 * @author lee9213@163.com
 * @version 1.0
 * @date 2017/3/17 17:52
 */
public class Server {

    private static SSLServerSocket sslServerSocket;

    /**
     * 初始化SSLServer
     * @throws Exception
     */
    public static void init() throws Exception {
        int port = 1234;

        //keystore中包含服务端的私钥与服务端的证书
        String keyStorePath = "/home/temp/ssl/server.keystore";
        String trustKeyStroePath = "/home/temp/ssl/ca-trust.keystore";
        String keyStorePassword = "123456";

        SSLContext sslContext = SSLContext.getInstance("SSL");

        //密钥库
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("sunx509");

        //信任库
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("sunx509");

        KeyStore keyStore = KeyStore.getInstance("pkcs12");
        KeyStore trustKeyStore = KeyStore.getInstance("jks");

        FileInputStream keyStoreFis = new FileInputStream(keyStorePath);
        keyStore.load(keyStoreFis, keyStorePassword.toCharArray());

        FileInputStream trustKeyStoreFis = new FileInputStream(trustKeyStroePath);
        trustKeyStore.load(trustKeyStoreFis, keyStorePassword.toCharArray());

        keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
        trustManagerFactory.init(trustKeyStore);

        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        sslServerSocket = (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(port);
        sslServerSocket.setNeedClientAuth(true);
    }

    /**
     * 处理SSL请求
     * @throws Exception
     */
    public static void process() throws Exception {
        String bye = "bye bye!";
        while (true) {
            Socket socket = sslServerSocket.accept();

            byte[] inputBytes = new byte[20];
            InputStream inputStream = socket.getInputStream();
            inputStream.read(inputBytes);

            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(bye.getBytes(), 0, bye.getBytes().length);
            outputStream.flush();
        }
    }
}
